<template>
  <div class="page-exportsetting">
    <Form class="export-form" label-position="top">
      <FormItem label="保存为">
        <Select :value="type" @on-change="changeType">
          <Option v-for="item in typeList" :value="item.value" :key="item.value">{{ item.label }}</Option>
        </Select>
      </FormItem>

      <FormItem label v-show="type==='spo' || type==='entity'">
        <Checkbox :value="autoCreate" @on-change="exportChange($event,'autoCreate')">自动创建缺失的概念、实体和属性</Checkbox>
      </FormItem>

      <FormItem label="输出路径" class="input-file" v-show="fileShow">
        <Input :value="fileUrl" placeholder="请选择" style="display:none" />
        <Input :value="fileName" placeholder="请选择" disabled />
        <i class="iconfont icon-file" @click="changeType" />
        <CodeSetting :code="fileUrl" />
      </FormItem>

      <FormItem label="数据来源">
        <RadioGroup :value="sourceType" @on-change="exportChange($event,'sourceType')">
          <Radio label="file" :disabled="readonly">文件</Radio>
          <Radio label="log" :disabled="readonly">系统日志</Radio>
        </RadioGroup>
      </FormItem>

      <FormItem :label="sourceConfigLabel" class="input-file">
        <AutoComplete
          :key="new Date().getTime()"
          :value="sourceConfig"
          @autoBlur="sourceConfigChange"
          :placeholder="sourceType === 'file' ? '请选择' : '请输入'"
          :readonly="readonly"
        />
        <i
          class="iconfont icon-file"
          v-if="sourceType === 'file' && !readonly"
          @click="filedataVisible=true"
        />

        <CodeSetting :code="sourceConfig" />
      </FormItem>
    </Form>

    <!-- 选择结构数据 -->
    <Modal footer-hide title="选择数据集数据" v-model="dsdataVisible" width="670px">
      <dsdata
        :fileUrl="fileUrl"
        :hidePreview="true"
        v-if="dsdataVisible"
        @cancelHandler="dsdataVisible=false"
        @okHandler="dsdataOkHandler"
      />
    </Modal>

    <!-- 选择图谱数据 -->
    <Modal
      footer-hide
      title="选择图谱数据"
      v-model="ceptdataVisible"
      width="800px"
      class="cept-workflow-modal"
    >
      <ceptdata
        :fileUrl="fileUrl"
        :hidePreview="true"
        v-if="ceptdataVisible"
        @cancelHandler="ceptdataVisible=false"
        @okHandler="ceptdataOkHandler"
      />
    </Modal>

    <!-- 选择文件数据 -->
    <Modal footer-hide title="选择文件数据" v-model="filedataVisible" width="700px">
      <filedata
        :filePath="sourceConfig"
        v-if="filedataVisible"
        @cancelHandler="filedataVisible=false"
        @okHandler="filedataOkHandler"
      />
    </Modal>
  </div>
</template>

<script>
import { wfCode } from 'assets/scripts/code';
import Dsdata from '../Common/Dsdata';
import Ceptdata from '../Common/Ceptdata';
import Filedata from '../Common/Filedata';
import AutoComplete from '../Common/AutoComplete';
import CodeSetting from '../Common/CodeSetting';

import { mapState, mapMutations } from 'vuex';
import { updateCustomNode } from 'http/api/workflow';

export default {
  props: ['nodeInfo'],
  components: {
    Dsdata,
    Ceptdata,
    Filedata,
    AutoComplete,
    CodeSetting
  },
  watch: {
    nodeInfo () {
      this.setNodeInfo();
    }
  },
  computed: {
    ...mapState({
      currentNode: state => state.workflow.currentNode,
      link: state => state.workflow.link,
      node: state => state.workflow.node
    })
  },
  data () {
    return {
      name: '',
      // 数据类型
      type: '',
      typeList: [
        {
          label: '数据集数据',
          value: 'ds'
        },
        {
          label: '图谱数据',
          value: 'cept'
        },
        {
          label: '图谱关系',
          value: 'relation'
        },
        {
          label: '实体数据',
          value: 'entity'
        },
        {
          label: 'SPO三元组',
          value: 'spo'
        }
      ],
      // 路径选择
      fileShow: true,
      dsdataVisible: false,
      ceptdataVisible: false,
      filedataVisible: false,
      pipelineId: '',
      sourceConfigLabel: '数据输入',

      // 请求参数
      sourceType: 'file',
      fileUrl: '',
      fileName: '',
      sourceConfig: '',
      readonly: false,
      autoCreate: false,
      showLogTip: '.*(?<result>{.*?}$)'
    };
  },
  methods: {
    ...mapMutations(['setNode']),

    // 控制状态
    setKeyValue (key, value) {
      this[key] = value;
    },

    // 重置编辑信息
    setNodeInfo () {
      let { argValues, name, id } = this.nodeInfo;
      if (argValues) {
        argValues = JSON.parse(argValues);
        let { sourceType, targetId, sourceConfig } = argValues;

        // targetId改造
        if (targetId) {
          this.type = targetId.type;
          this.fileUrl = targetId.id;
          this.fileName = targetId.name;
          this.autoCreate = targetId.autoCreate ? targetId.autoCreate : false;
        }

        this.sourceType = sourceType;
        this.sourceConfigLabel =
          this.sourceType === 'file'
            ? '数据输入'
            : 'log正则（正则必须存在result分组）';
        this.sourceConfig = sourceConfig;
        this.name = name;

        if (this.sourceType === 'log') {
          this.sourceConfig = this.sourceConfig
            ? this.sourceConfig
            : this.showLogTip;
        }

        let type = this.type;
        if (type === 'relation' || type === 'spo' || type === 'entity') {
          this.dsdataVisible = false;
          this.ceptdataVisible = false;
          this.fileShow = false;
        }
      }
      this.readonly = false;
      this.setReadOnly(id);
    },

    // 当数据流组件连接到保存节点的时候，自动设置保存数据的信息，且不能修改/workspace/ds/上一节点id_端点index
    setReadOnly (id) {
      this.link.forEach(item => {
        if (item.end === id) {
          let startId = item.start;
          if (this.node[startId].systemNode) {
            let { dataFlow, outputPorts } = this.node[startId].systemNode;
            if (dataFlow) {
              this.readonly = true;
              let index = outputPorts[item.srcIndex].index;
              let newConfig = `/workspace/ds/${startId}_${index}`;
              if (this.sourceConfig !== newConfig) {
                this.sourceConfig = newConfig;
                this.updateNodeInfo();
              }
            }
          }
        }
      });
    },

    // 选择数据
    dsdataOkHandler ({ id, name }) {
      this.fileUrl = id;
      this.fileName = name;

      this.dsdataVisible = false;
      this.exportChange(id, 'fileUrl');
    },

    // 图谱数据
    ceptdataOkHandler ({ id, name }) {
      this.fileUrl = id;
      this.fileName = name;

      this.ceptdataVisible = false;
      this.exportChange(id, 'fileUrl');
    },

    // 文件路径选中后
    filedataOkHandler (filePath) {
      this.sourceConfig = filePath;
      this.filedataVisible = false;
      this.updateNodeInfo();
    },

    // sourceConfig更改
    sourceConfigChange (val) {
      this.exportChange(val, 'sourceConfig');
    },

    // 输入更改
    exportChange (e, name) {
      let nodeName = e.target && e.target.nodeName;
      let value;
      if (nodeName === 'INPUT') {
        value = e.target.value;
      } else {
        value = e;
      }

      if (typeof e === 'boolean') {
        value = e;
      }

      if (name === 'sourceType') {
        this.sourceConfigLabel =
          value === 'file' ? '数据输入' : 'log正则（正则必须存在result分组）';

        if (value === 'log') {
          this.sourceConfig = this.showLogTip;
        } else {
          this.sourceConfig = ''
        }
      }

      this[name] = value;

      // 请求更新
      this.updateNodeInfo();
    },

    // 数据类型选择
    changeType (v) {
      let type = typeof v === 'string' ? v : this.type;

      if (!type) {
        this.$Message.error('请选择数据类型');
        return;
      }

      this.type = type;

      this.fileUrl = '';
      this.fileName = '';
      this.autoCreate = false;

      // 数据结构
      if (type === 'ds') {
        this.dsdataVisible = true;
        this.fileShow = true;
      }

      if (type === 'cept') {
        this.ceptdataVisible = true;
        this.fileShow = true;
      }

      // 数据清空
      if (typeof v === 'string') {
        this.fileUrl = '';
      }

      // 图谱关系
      if (type === 'relation' || type === 'spo' || type === 'entity') {
        this.dsdataVisible = false;
        this.ceptdataVisible = false;
        this.fileShow = false;
        this.updateNodeInfo();
      }
    },

    /**
     * 输出数据的参数argValues
     * 请求更新节点的接口
     */
    updateNodeInfo () {
      let { x, y, id } = this.currentNode;

      let obj = {
        targetId: {
          type: this.type,
          id: this.fileUrl,
          name: this.fileName,
          autoCreate: this.autoCreate
        },
        sourceType: this.sourceType,
        sourceConfig: this.sourceConfig
      };
      let param = {
        id: id,
        location: { x, y },
        pipeline: {
          id: this.pipelineId
        },
        argValues: JSON.stringify(obj)
      };

      let wires = [];
      this.link.forEach(item => {
        let { start, end, srcIndex, desIndex } = item;
        if (start === id) {
          wires.push({
            srcId: start,
            desId: end,
            desIndex: desIndex || 0,
            srcIndex: srcIndex || 0
          });
        }
      });

      param.wires = wires;
      param.pipelineTaskNodeType = wfCode.EXPORT;
      // 先改数据
      this.node[id] = Object.assign({}, this.node[id], param);
      this.setNode(this.node);

      updateCustomNode(param).then(res => {
        this.node[id] = Object.assign({}, this.node[id], res.data);
        this.setNode(this.node);
      });
    }
  },
  mounted () {
    this.pipelineId = this.$route.query.pipelineId;

    // 节点编辑信息
    if (this.nodeInfo) {
      this.setNodeInfo();
    }
  }
};
</script>

<style rel="stylesheet/less" lang="less" scoped>
.page-exportsetting {
  padding: 2px 0;
  .export-form {
    margin-top: 20px;
    padding-left: 20px;
    padding-right: 20px;
    min-height: 450px;
  }
  .view-btns {
    float: right;
    padding-right: 10px;
  }
}
</style>
